//
//  PywPayViewController.m
//  PywSdk
//
//  Created by Jade on 16/7/21.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywPayViewController.h"

#import "PywSdk+pay.h"
#import "PywMBProgressHUD+Pyw.h"

#import "PywMasonry.h"
#import "PywAppInfo.h"
#import "PywIAPHelper.h"
#import "PywPayInfoModel.h"
#import "PywCPNotifications.h"

#import "PywCouponListApi.h"
#import "PywCreateOrderApi.h"

#import "PywCoupon.h"
#import "PywPayHeadView.h"
#import "PywPayFootView.h"
#import "PywPayBottomView.h"


#import "PywNavgationController.h"
#import "PywInputPayPwdController.h"
#import "PywSelectCouponController.h"
#import "PywWebPayViewController.h"
#import "PywBindGetSMSCodeController.h"

@interface PywPayViewController ()
{
    NSInteger _payWays;//支付方式数量
}
@property (nonatomic,strong) UITableView *mainTable;
@property (nonatomic,strong) PywPayHeadView         *payHeadView;
@property (nonatomic,strong) PywPayFootView         *payFootView;
@property (nonatomic,strong) PywPayBottomView       *payBottomView;
@property (nonatomic,strong) PywPayInfoModel        *payInfoModel;

@property (nonatomic,assign) BOOL                   isOpenApplePay;

@property (nonatomic,strong) PywCreateOrderApi      *createOrderApi;
@property (nonatomic,strong) PywCouponListApi       *couponListApi;
@end

@implementation PywPayViewController


- (instancetype)initWithPayInfo:(NSDictionary *)payInfo
{
    self = [super init];
    if (self) {
        self.isOpenApplePay = [PywAppInfo sharedAppInfo].is_applepay;
        [self setUpPayInfoModel:payInfo];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUp];
}

#pragma mark - init

- (void)setUp
{
    self.title = @"支付中心";
    self.navigationItem.rightBarButtonItem = nil;
    [self.view addSubview:self.mainTable];
    [self.view addSubview:self.payBottomView];
    [self addConstraints];
    [self addNotifications];
    if (self.payInfoModel.coupon_count == 0) {
        [self.payHeadView updateCouponPrompt];
    }
}

- (void)addNotifications
{
    //      通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payFinish:)
                                                 name:kPywPayNotification
                                               object:nil];
}

- (void)addConstraints
{
    WEAK_SELF;
    [self.mainTable mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.bottom.offset(-50);
    }];
    [self.payBottomView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        STRONG_SELF(weakSelf);
        make.bottom.equalTo(strongSelf.view.mas_bottom);
        make.left.right.equalTo(strongSelf.view);
        make.height.equalTo(@50);
    }];
}

#pragma mark - getter
- (PywCouponListApi *)couponListApi
{
    if (!_couponListApi) {
        _couponListApi = [PywCouponListApi manager];
    }
    return _couponListApi;
}

- (PywCreateOrderApi *)createOrderApi
{
    if (!_createOrderApi) {
        _createOrderApi = [PywCreateOrderApi manager];
    }
    return _createOrderApi;
}

/**
 *  赋值支付参数信息
 *
 *  @param payInfo <#payInfo description#>
 */
- (void)setUpPayInfoModel:(NSDictionary *)payInfo
{
    PywPayInfoModel *payInfoModel = [[PywPayInfoModel alloc] init];
    payInfoModel.order = payInfo[@"order_id"];
    payInfoModel.amount = [payInfo[@"oriprice"] floatValue];
    payInfoModel.payMethod = self.isOpenApplePay?PAY_WAY_TYPE_APPLE:PAY_WAY_TYPE_ALIPAY;
    payInfoModel.couponAmount = 0.00;
    payInfoModel.finalAmount = payInfoModel.amount - payInfoModel.couponAmount;
    payInfoModel.productDescript = payInfo[@"gameBi"];
    payInfoModel.cpprams = payInfo[@"cpprams"];
    payInfoModel.cpprodid = payInfo[@"cpprodid"];
    payInfoModel.coupon_count = [payInfo[@"coupon_count"] integerValue];
    payInfoModel.pay_url = payInfo[@"pay_url"];

    [PywAppInfo sharedAppInfo].payType = PayTypeFix;
    if (payInfoModel.cpprodid.length == 0) {
        [PywAppInfo sharedAppInfo].payType = PayTypeAny;
    }
    payInfoModel.rolename = payInfo[@"rolename"];
    payInfoModel.service = payInfo[@"service"];
    payInfoModel.roleid = payInfo[@"roleid"];
    payInfoModel.serverArea = payInfo[@"serverArea"];
    
    self.payInfoModel = payInfoModel;
}

- (UITableView *)mainTable
{
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] init];
        _mainTable.tableHeaderView = self.payHeadView;
        if ([PywAppInfo sharedAppInfo].pay_type_order.length > 0) {
            _mainTable.tableFooterView = self.payFootView;
        }else {
            _mainTable.tableFooterView = [[UIView alloc] init];
        }
        _mainTable.backgroundColor = RGB(232, 232, 232, 1);
    }
    return _mainTable;
}

- (PywPayHeadView *)payHeadView
{
    if (!_payHeadView) {
        WEAK_SELF;
        _payHeadView = [[PywPayHeadView alloc] initWithPayInfo:self.payInfoModel
                                                  selectCoupon:^{
                                                      STRONG_SELF(weakSelf);
                                                      [strongSelf skipCouponView];
                                                  }];
    }
    return _payHeadView;
}

- (PywPayBottomView *)payBottomView
{
    if (!_payBottomView) {
        WEAK_SELF;
        _payBottomView = [[PywPayBottomView alloc] initWithMoney:self.payInfoModel.finalAmount Finish:^{
            STRONG_SELF(weakSelf);
            [strongSelf selectPayBtn];
        }];
    }
    return _payBottomView;
}

- (PywPayFootView *)payFootView
{
    if (!_payFootView) {
        WEAK_SELF;
        _payFootView = [[PywPayFootView alloc] initWithSelectPayWays:^(NSInteger payWay) {
            STRONG_SELF(weakSelf);
            strongSelf.payInfoModel.payMethod = payWay;
        }];
    }
    return _payFootView;
}

#pragma mark - Interface Method

// 竖屏布局
- (void)verticalScreenControlsDistribution
{
    [self.payFootView reloadFootViewPortrait:YES];
}

// 横屏布局
- (void)horizontalScreenControlsDistribution
{
    [self.payFootView reloadFootViewPortrait:NO];
}

#pragma mark - Actions

- (void)returnback
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywPayNotification
                                                        object:[NSNumber numberWithBool:YES]];
    
    [PywMBProgressHUD hideHUD];
}

/**
 *  跳转到代金券页面
 */
- (void)skipCouponView
{
    PywSelectCouponController * couponVC =  [[PywSelectCouponController alloc] initWithAmount:self.payInfoModel.amount];
    __block CGFloat couponAmount = 0;
    couponVC.getAmountBlock = ^(NSMutableArray *coupons){
        [self.payInfoModel.couponNumbers removeAllObjects];
        self.payInfoModel.couponAmount = 0.00;
        [coupons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PywCoupon *coupon = (PywCoupon *)obj;
            couponAmount = couponAmount + [coupon.amount floatValue];
            [self.payInfoModel.couponNumbers addObject:coupon.code];
        }];
        couponAmount = couponAmount<=0?self.payInfoModel.couponAmount:couponAmount;
        couponAmount = couponAmount>self.payInfoModel.amount?self.payInfoModel.amount:couponAmount;
        self.payInfoModel.couponAmount = couponAmount;
        
        self.payInfoModel.finalAmount = self.payInfoModel.amount - self.payInfoModel.couponAmount;
        
        [self showOrHidePayWays];
    };
    [self.navigationController pushViewController:couponVC animated:YES];
    
}

- (void)selectPayBtn
{
    if ([PywAppInfo sharedAppInfo].pay_type_order.length == 0) {
        [PywMBProgressHUD showError:@"支付失败！"];
        return;
    }

    Boolean has_pay_pwd = [PywPlatformMain sharedPlatformMain].is_have_pay_pwd;
    Boolean usedCoupon = self.payInfoModel.couponAmount > 0;

    if (usedCoupon && has_pay_pwd) {//弹出交易密码
    NSString *failPayAmount = [NSString stringWithFormat:@"￥%@", [NSString stringWithFormat:@"%.2f", self.payInfoModel.finalAmount]];
    NSString *couponPayAmount = [NSString stringWithFormat:@"￥%@", [NSString stringWithFormat:@"%.2f", self.payHeadView.couponAmount]];
    [[PywInputPayPwdController alloc] showInViewController:self
                                             failPayAmount:failPayAmount
                                           couponPayAmount:couponPayAmount
                                       checkPayPwdComplete:^{
                                               [self getCreateOrderData];
                                           }];
    }else {// 交易
        [self getCreateOrderData];
    }
}
/**
 *  显示与隐藏  支付方式
 */
- (void)showOrHidePayWays{
    self.payHeadView.couponAmount = self.payInfoModel.couponAmount;
    [self.payBottomView reloadPayMoney:self.payInfoModel.finalAmount];
    
    if (self.payInfoModel.finalAmount <= 0) {
        self.mainTable.tableFooterView.hidden = YES;
    }else {
        self.mainTable.tableFooterView.hidden = NO;
    }
}

#pragma mark - Notifications

/**
 *  支付成功回调
 *
 *  @param notification <#notification description#>
 */
- (void)payFinish:(NSNotification *)notification
{
    BOOL hideHUD = [notification.object boolValue];
    if (!hideHUD) {
        [PywMBProgressHUD showSuccess:@"支付完成"];
    }
    [self dismissViewControllerAnimated:YES completion:^{
        //支付Cp回调
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:@"支付完成" forKey:@"info"];
        [dict setObject:[NSNumber numberWithInt:PYW_PAY_STATE_SUCCESS] forKey:@"result"];
        NSString *notificationName = [PywAppInfo sharedAppInfo].payType == PayTypeAny?kPywCPAnyPayNotification:kPywCPPayNotification;
        [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
                                                            object:nil
                                                          userInfo:dict];
        
        // 当聚合直接调用支付时，支付完成后，需要清除以下字段的存储
        if ([PywPlatformMain sharedPlatformMain].perfromPayType == PerfromPayType_Common) {
            [PywPlatformMain sharedPlatformMain].account = @"";
            [PywPlatformMain sharedPlatformMain].token = @"";
            [PywAppInfo sharedAppInfo].gameKey = @"";
            [PywAppInfo sharedAppInfo].gameId = @"";
            [PywAppInfo sharedAppInfo].apisecret = @"";

        }
    }];
}


#pragma mark - Request

/**
 *  请求代金券列表
 */
- (void)requestCouponList
{
    WEAK_SELF;
    [self.couponListApi getCouponListWithStatus:2 page:1 success:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        NSDictionary *orderDict = (NSDictionary *)anyObjct;
        NSInteger ack = [[orderDict objectForKey:@"ack"] integerValue];
        if (ack == 200) {
            NSArray *list = [[orderDict objectForKey:@"data"] objectForKey:@"list"];
            NSArray *coupons = [PywCoupon arrayOfModelsFromDictionaries:list error:nil];
            if (coupons.count == 0) {
                [strongSelf.payHeadView updateCouponPrompt];
            }
        }else {
            [strongSelf.payHeadView updateCouponPrompt];
        }
    } fail:^(NSError *error) {
        [weakSelf.payHeadView updateCouponPrompt];
    }];
}
/**
 *  生成订单
 */
- (void)getCreateOrderData
{
    [self.payBottomView switchPayStuatus:NO];
    [PywMBProgressHUD showMessage:@"正在支付..."];
    WEAK_SELF;
    [self.createOrderApi getCreateOrderWithPayInfo:self.payInfoModel success:^(NSString *status, id anyObjct) {
        NSDictionary *orderDict = (NSDictionary *)anyObjct;
        [weakSelf requestCreateOrderSuccess:orderDict];
    } fail:^(NSError *error) {
        [weakSelf.payBottomView switchPayStuatus:YES];
    }];
}


#pragma mark - request finish
/**
 *  生成订单请求成功
 *
 *  @param dict <#dict description#>
 */
- (void)requestCreateOrderSuccess:(NSDictionary *)dict
{
    [self.payBottomView switchPayStuatus:YES];
    int resultCode = [[dict objectForKey:@"ack"] intValue];
    if (resultCode == 200) {
        Boolean msg = [dict[@"msg"] intValue];
        if (msg == 0) { //纯代金券支付
            [[NSNotificationCenter defaultCenter] postNotificationName:kPywPayNotification
                                                                object:nil];
        }
        else {
            [self thirdPayCreateorderWithPayCode:dict];
        }
    }else{
        [PywMBProgressHUD showError:@"创建订单失败"];
    }
}
/**
 *  三方支付生成订单成功
 */
- (void)thirdPayCreateorderWithPayCode:(NSDictionary *)dict
{
    self.payInfoModel.orderNum = [self orderNumWithDict:dict];
    [self openWebPayWithPayInfo];
}

- (NSString *)orderNumWithDict:(NSDictionary *)dict
{
    switch (self.payInfoModel.payMethod) {
        case PAY_WAY_TYPE_ALIPAY:
        {
            NSString *payCode = dict[@"data"];
            //需要使用第三方支付
            NSRange range = [payCode rangeOfString:@"out_trade_no="];
            if (range.location != NSNotFound) {
                return [payCode substringWithRange:NSMakeRange(range.location + range.length + 1, 16)];
            }
            return nil;
        }
            break;
        case PAY_WAY_TYPE_UNION:
        {
            return dict[@"data"][@"orderNum"];
        }
            break;
        case PAY_WAY_TYPE_WECHAT:
        {
            return dict[@"data"][@"order_sn"];
        }
            break;
            
        default:
            return nil;
            break;
    }
}

/**
 *  H5支付
 */
- (void)openWebPayWithPayInfo
{
    MutableDictionary *dictionary = [[MutableDictionary alloc] init];
    [dictionary setObject:self.payInfoModel.orderNum forKey:@"out_trade_no"];
    [dictionary setObject:[PywPlatformMain sharedPlatformMain].userName forKey:@"userid"];
    [dictionary setObject:@(self.payInfoModel.finalAmount) forKey:@"total_fee"];
    [dictionary setObject:[PywPlatformMain sharedPlatformMain].token forKey:@"token"];
    [dictionary setObject:@"IOS" forKey:@"device_info"];
    [dictionary setObject:self.payInfoModel.pay_url forKey:@"pay_url"];
    
    
    PywWebPayViewController *wxWebPayView = [[PywWebPayViewController alloc] initRequestPayInfo:dictionary];
    [self.navigationController pushViewController:wxWebPayView animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
